// JavaScript Document
$(function(){
    $(".check-coupons").slide({mainCell:".bd"});

    $("#Coupons").off().on("click",function(e){
        e.stopPropagation();
        var checkCoupons=$(this).parents(".checkout-count-extend").find(".check-coupons");
        if(this.checked){
            checkCoupons.show();
        }else{
            checkCoupons.hide();
			changeBonus(0); // 取消选择优惠券
			$('#ECS_BONUS option:first').prop("selected",'selected');
			document.forms['theForm'].elements['bonus_sn'].value = '';
        }
    });
    $('input[name="need_inv"]').off().on("click",function(e){
        if($(this).val()==0){
            $(this).parent("li.item").siblings("li").hide();
        }else{
            $(this).parent("li.item").siblings("li").not("#CompanyName").show();
            if($('input[name="inv_payee"]:checked').val()=="单位"){
                $("#CompanyName").show();
            }
        }
    });
    $('input[name="inv_payee"]').off().on("click",function(e){
            if($(this).val()=='单位'&&$('input[name="need_inv"]:checked').val()==1){
                $("#CompanyName").show();
            }else{
                $("#CompanyName").hide();
            }
        });
    $(".coupons-box .submit").off().on("click",function(){

        validateBonus(1,document.forms['theForm'].elements['bonus_sn'].value,document.forms['theForm'].elements['bonus_type_ids'].value);
		$('#ECS_BONUS option:first').prop("selected",'selected');
    })
    $(".coupons-box .reset").off().on("click",function(){
        changeBonus(0);
		$('#ECS_BONUS option:first').prop("selected",'selected');
		document.forms['theForm'].elements['bonus_sn'].value = '';
    })
    $("#orderNow").off().on("click",function(){
		var m = $("#orderNow").attr("data-val");
        if(m == 0){
			checkOrderForm(document.forms['theForm']);
            return true;
        }else{
            return false;
        }
    })

    /* *
     * 检查提交的订单表单
     */
    function checkOrderForm(frm)
    {
        var _this=this;
        var b = $("#checkoutAddrList").find(".checked-on").length;
        if (0 >= b) return alert("请选择收货地址!"), $(window).scrollTop(0);

        if ($("#Invoice").val()==1&&$("#Company").val()==1&&$('input[name="inv_payee_info"]').val()==""){
              alert("请填写单位名称!");
            return false;

        };
        if(document.getElementById("Coupons").checked && $('input[name="bonus_sn"]').val() == "" && $('#ECS_BONUS option:selected').val() == 0){
            alert("请填写优惠券号码或取消勾选使用优惠券选项！");
            return false;
        }

        var shippingSelected = false;

        // 检查是否选择了支付配送方式
        for (i = 0; i < frm.elements.length; i ++ )
        {
            if (frm.elements[i].name == 'shipping' && frm.elements[i].checked)
            {
                shippingSelected = true;
            }

        }

        if ( ! shippingSelected)
        {
            alert('请选择配送方式！');
            return false;
        }

		$("#orderNow").attr("disabled",true).css({cursor:"default",background:"#dfdfdf",border:"1px solid #dfdfdf"});
		$("#orderNow").attr("data-val",1);
        frm.action = 'flow.php?step=done';
		frm.submit();
        return true;
    };

    /**
     * 验证红包序列号
     * @param string bonusSn 红包序列号
     */
    function validateBonus(type,bonusSn,bonus_type_ids)
    {
		var timeSe = new Date().getTime()/1000;
        $.get('flow.php?step=validate_bonus','type='+type+ '&bonus_sn=' + bonusSn + '&bonus_type_ids=' + bonus_type_ids+"&timeSe="+timeSe, validateBonusResponse,  'JSON');
    }
})

/* *
 * 改变红包
 */
function changeBonus(val)
{
	var timeSe = new Date().getTime()/1000;
	document.forms['theForm'].elements['bonus_sn'].value = '';
    $.get('flow.php?step=change_bonus', 'bonus=' + val+"&timeSe="+timeSe, changeBonusResponse,  'JSON');
}

/* *
 * 改变红包的回调函数
 */
function changeBonusResponse(obj)
{
    if (obj.error)
    {
        alert(obj.error);

        try
        {
            document.getElementById('ECS_BONUS').value = '0';
        }
        catch (ex) { }
    }
    else
    {
        orderSelectedResponse(obj.content);
    }
}

function validateBonusResponse(obj)
{

	if (obj.error)
	{
		alert(obj.error);
		orderSelectedResponse(obj.content);
		try
		{
			document.getElementById('ECS_BONUSN').value = '0';
		}
		catch (ex) { }
	}
	else
	{
		alert(obj.title);
		orderSelectedResponse(obj.content);
	}
}
/* *
* 回调函数
*/
function orderSelectedResponse(result)
{
    if (result.error)
    {
        alert(result.error);
        location.href = './';
    }

    try
    {
        var layer = document.getElementById("checkout-price");
        layer.innerHTML = (typeof result == "object") ? result.content : result;
    }
    catch (ex) { }
}
var selectedShipping = null;
/* *
 * 改变配送方式
 */
function selectShipping(obj)
{
    if (selectedShipping == obj)
    {
        return;
    }
    else
    {
        selectedShipping = obj;
    }

	if($("#Coupons").prop('checked') == true) {
	    $("#Coupons").trigger("click");
	}

	var timeSe = new Date().getTime()/1000;
    $.get('flow.php?step=select_shipping', 'shipping=' + obj.value+"&timeSe="+timeSe, orderShippingSelectedResponse,  'JSON');
}

/**
 *
 */
function orderShippingSelectedResponse(result)
{

    if (result.need_insure)
    {
        try
        {
            document.getElementById('ECS_NEEDINSURE').checked = true;
        }
        catch (ex)
        {
            alert(ex.message);
        }
    }
    orderSelectedResponse(result);
}